package com.yupi.ojjudge.judge;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.yupi.ojjudge.common.ErrorCode;
import com.yupi.ojjudge.exception.BusinessException;
import com.yupi.ojjudge.judge.codesandbox.CodeSandBox;
import com.yupi.ojjudge.judge.codesandbox.CodeSandBoxFactory;
import com.yupi.ojjudge.judge.codesandbox.CodeSandBoxProxy;
import com.yupi.ojjudge.judge.model.ExecuteCodeRequest;
import com.yupi.ojjudge.judge.model.ExecuteCodeResponse;
import com.yupi.ojjudge.judge.strategy.JudgeContext;
import com.yupi.ojjudge.model.dto.question.JudgeCase;
import com.yupi.ojjudge.judge.model.JudgeInfo;
import com.yupi.ojjudge.model.entity.Question;
import com.yupi.ojjudge.model.entity.QuestionSubmit;
import com.yupi.ojjudge.model.enums.QuestionSubmitStatusEnum;
import com.yupi.ojjudge.service.QuestionService;
import com.yupi.ojjudge.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author ortonzhu
 * @Date 2024/10/19 11:19
 */
@Service
public class JudgeServiceImpl implements JudgeService {
    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private QuestionService questionService;

    @Value("${codesandbox.type:example}")
    private String type;

    /**
     * 判题服务
     *
     * @param questionSubmitId
     * @return
     */
    @Override
    public QuestionSubmit doJudge(Long questionSubmitId) {
        // 1.获取信息
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        Optional.ofNullable(questionSubmit).orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "提交记录不存在"));
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if (ObjectUtil.isEmpty(question)) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        // 如果不为等待状态
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITING.getValue())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "题目正在判题");
        }
        // 更改判题（题目提交）的状态为“判题中”，防止重复执行，也能让用户即时看到状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        String language = questionSubmit.getLanguage();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean updateById = questionSubmitService.updateById(questionSubmitUpdate);
        if (!updateById) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "提交记录更新失败");
        }
        // 4.调用沙箱，获取执行结果
        String code = questionSubmit.getCode();
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(type);
        CodeSandBoxProxy codeSandBoxProxy = new CodeSandBoxProxy(codeSandBox);
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest
                .builder()
                .code(code)
                .language(language)
                .inputList(inputList)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSandBoxProxy.executeCode(executeCodeRequest);
        // 判断判题结果
        List<String> outputList = executeCodeResponse.getOutputList();
        // 5. 根据沙箱的执行结果，设置题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        // 判断使用那些方法
        JudgeManage judgeManage = new JudgeManage();
        JudgeInfo judgeInfo = judgeManage.doJudge(judgeContext);
        // 修改判题结果
        QuestionSubmit questionSubmitNew = QuestionSubmit.builder()
                .id(questionSubmitId)
                .status(QuestionSubmitStatusEnum.SUCCEED.getValue())
                .judgeInfo(JSONUtil.toJsonStr(judgeInfo))
                .build();
        boolean update = questionSubmitService.updateById(questionSubmitNew);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新失败");
        }
        return questionSubmitService.getById(questionSubmitId);
    }
}
